<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="600"
    @close="handleCancel(formRef)"
  >
    <template #title>标签</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item
          field="tag"
          label="标签"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-select
            v-model="formData.tag"
            size="small"
            allow-create
            placeholder="请选择标签"
          >
            <ga-option
              v-for="(item, idx) in tagList"
              :key="idx"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </ga-select>
        </ga-form-item>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, reactive } from "vue";
import { editTagList, getTagList } from "@/api/tagMgmt.ts";
import { Message } from "@garco-design/web-vue";
import { RULE } from "@/constant/validators";
import useLoading from "@/hooks/loading";

const { loading, setLoading } = useLoading(false);
const formRef = ref(null)
const formData = reactive({
  tag: '',
});

const visible = ref(false);
const curId = ref("");
const tagList = ref([]);
const open = async (val) => {
  // console.log("val------", val);
  visible.value = true;
  if (val && val?.id) {
    setLoading(true);
    curId.value = val.id;
    formData.tag = val?.storageType?.dictValue;
    const { data } = await getTagList({ dictType: "storage_type", limit: -1 });
    tagList.value = data?.items;
    setLoading(false);
  }
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    try {
      const obj = [{
        dictType: "storage_type",
        dictValue: formData.tag
      }]
      const { code } = await editTagList(curId.value, obj)
      if (code === 20000) Message.success("操作成功")
      emits("fetchData")
    } finally {
      visible.value = false
    }
  }
};
const handleCancel = (formEl) => {
  curId.value = "";
  formEl.resetFields();
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
